package com.devsoft.foodfrenzy;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ScoreManager extends SQLiteOpenHelper{

       static final String dbName = "myDB";
       static final String tLevels = "Levels";
       static final String fLevelID = "levelNum";
       static final String fHighScore = "highScore";
       static final String fAchvmUnLocked = "achvmLocked";

      
       public ScoreManager(Context context) {
               super(context, dbName, null, 1);
       }

       @Override
       public void onCreate(SQLiteDatabase db) {
               db.execSQL("CREATE TABLE IF NOT EXISTS "+tLevels+" (" +
                                       fLevelID + " INTEGER PRIMARY KEY , " +
                                       fHighScore + " TEXT " +
                                       fAchvmUnLocked  + "TEXT" +
                                       ")");
       
                ContentValues cv = new ContentValues();
                       cv.put(fLevelID, 1);
                       cv.put(fAchvmUnLocked , "false");
                       cv.put(fHighScore, "0");
                               db.insert(tLevels, null, cv);
                                                                  
       }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               db.execSQL("DROP TABLE IF EXISTS "+tLevels);
               onCreate(db);
       }
      
        public int readHighScore(int ID) {               
                SQLiteDatabase myDB = this.getReadableDatabase();
                String[] mySearch = new String[]{String.valueOf(ID)};
                Cursor myCursor = myDB.rawQuery("SELECT "+ fHighScore  +" FROM "+ tLevels +" WHERE "+ fLevelID +"=?",mySearch);
                myCursor.moveToFirst();
                int index = myCursor.getColumnIndex(fHighScore);
                String myAnswer = myCursor.getString(index);
                myCursor.close();
                int HighScore = Integer.valueOf(myAnswer);
                return HighScore;
        }
        
        public int writeHighScore(int ID, String newHigScore)
        {        
                SQLiteDatabase myDB = this.getWritableDatabase();
                ContentValues cv = new ContentValues();
                cv.put(fHighScore, newHigScore);
                int numRowsAffected = myDB.update(tLevels, cv, fLevelID+"=?", new String []{String.valueOf(ID)});
                return numRowsAffected;
        }
              
}


